package vip.xiaonuo.smzq.modular.nbfb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.smzq.core.gson.GsonUtil;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.core.utils.StringUtilTool;
import vip.xiaonuo.smzq.modular.hisi.entity.vo.KcdgmtjVo;
import vip.xiaonuo.smzq.modular.kcl.entity.Zycl;
import vip.xiaonuo.smzq.modular.nbfb.entity.param.NbfbSixParam;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.KcdKccdtjVo;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.NbfbSevenVo;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.NbfbSixVo;
import vip.xiaonuo.smzq.modular.nbfb.mapper.ZyclSevenMapper;
import vip.xiaonuo.smzq.modular.nbfb.service.INbfbSevenService;
import vip.xiaonuo.smzq.modular.user.entity.Role;
import vip.xiaonuo.smzq.modular.user.mapper.RoleMapper;
import vip.xiaonuo.sys.modular.role.enums.SysRoleEnum;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class NbfbSevenServiceImpl extends ServiceImpl<ZyclSevenMapper, Zycl> implements INbfbSevenService {
    @Resource
    private ZyclSevenMapper zyclSevenMapper;
    @Resource
    private RoleMapper roleMapper;// 角色表
    /**
     * 查询年报附表7
     * SQQ
     * @return
     */
    @Override
    public List<NbfbSevenVo> getNbfbSeven(NbfbSixParam param) {
        //特殊矿种
        String[] array = {"42201", "42202", "32006", "63701"};
        List<NbfbSevenVo> nbfbSevenVoList = new ArrayList<>();
        //特殊矿种分类
        List<NbfbSevenVo> tsvoList = new ArrayList<>();

        Integer nd = param.getNd();
        String kcdmStr = param.getKcdm();
        // List<String> list = Arrays.asList(kcdmStr.split(","));
        //查询年度附表6数据
        List<KcdKccdtjVo> nbfbSevenList =new ArrayList<>();

        //获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        Role role = roleMapper.selectById(saBaseLoginUser.getPositionId());

        if (SysRoleEnum.ADMIN.getValue().equals(role.getCode()) || SysRoleEnum.BJSH.getValue().equals(role.getCode()) || SysRoleEnum.SHENGSH.getValue().equals(role.getCode())) {
            nbfbSevenList = zyclSevenMapper.getNbfbseven(nd);
        }

        if (nbfbSevenList.size()==0){
            return nbfbSevenVoList;
        }


        //根据矿种分组
        Map<String, List<KcdKccdtjVo>> groupMap = nbfbSevenList.stream().collect(Collectors.groupingBy(KcdKccdtjVo::getBz));
        for (Map.Entry<String, List<KcdKccdtjVo>> entry : groupMap.entrySet()) {
            NbfbSevenVo vo = new NbfbSevenVo();
            List<KcdKccdtjVo> sevenList = entry.getValue();
            String bz = entry.getKey();
            String kcdm = StringUtilTool.extractMiddlePart(bz);
            if (kcdmStr != null && !kcdmStr.equals("")) {
                //是否包含特殊矿种
                if (Arrays.toString(array).contains(kcdm) && kcdmStr.contains(kcdm)) {
                    if (CollectionUtil.isNotEmpty(sevenList)) {
                        vo.setBz(sevenList.get(0).getBz());
                        vo.setKcmc(sevenList.get(0).getKcmc());
                        vo.setDw(sevenList.get(0).getDw());
                    }
                    List<KcdKccdtjVo> dataList = GsonUtil.ObjectToList(sevenList, KcdKccdtjVo.class);
                    vo.setKcdkccdjList(dataList);
                    tsvoList.add(vo);
                } else {
                    if (kcdmStr.contains(bz)) {
                        if (CollectionUtil.isNotEmpty(sevenList)) {
                            vo.setBz(sevenList.get(0).getBz());
                            vo.setKcmc(sevenList.get(0).getKcmc());
                            vo.setDw(sevenList.get(0).getDw());
                        }
                        List<KcdKccdtjVo> dataList = GsonUtil.ObjectToList(sevenList, KcdKccdtjVo.class);
                        vo.setKcdkccdjList(dataList);
                        nbfbSevenVoList.add(vo);
                    }
                }
            }
        }
        nbfbSevenVoList.addAll(tsvoList);
        // 根据 getBz() 方法的结果对列表进行排序
        return nbfbSevenVoList.stream()
                .sorted(Comparator.comparing(NbfbSevenVo::getBz))
                .collect(Collectors.toList());
    }


    /**
     * 年报附表7导出
     * SQQ
     */
    @Override
    public void exportNbfbSevenExcel(NbfbSixParam param, HttpServletResponse response) {
        //查询数据
        List<NbfbSevenVo> nbfbSevenVoList = getNbfbSeven(param);

        // 设置响应头字符集为UTF-8
        response.setCharacterEncoding("utf-8");
        // 设置响应头，指定下载文件名
        response.setContentType("application/octet-stream; charset=UTF-8");

        // 加载模板文件
        ClassPathResource classPathResource = new ClassPathResource(PathUtils.getNbfbPath(11));
        InputStream inputStream = null;
        try {
            // 从资源路径获取输入流
            inputStream = classPathResource.getStream();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 创建XSSFWorkbook对象来操作Excel文件
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 设置第一个sheet的名称
        workbook.setSheetName(0, nbfbSevenVoList.get(0).getKcmc());

        // 复制第一个sheet到其他sheet
        for (int i = 1; i < nbfbSevenVoList.size(); i++) {
            workbook.cloneSheet(0, nbfbSevenVoList.get(i).getKcmc());
        }

        // 将工作簿写入字节数组输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            workbook.write(baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();

        // 使用字节数组创建输入流
        InputStream templateStream = new ByteArrayInputStream(bytes); // 使用不同的变量名

        // 使用EasyExcel创建ExcelWriter对象
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(response.getOutputStream())
                    .withTemplate(templateStream)
                    .build();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 遍历数据列表
        int index = 0;
        for (NbfbSevenVo nbfbSixVo : nbfbSevenVoList) {
            index++;
            // 创建WriteSheet对象
            WriteSheet writeSheet = EasyExcel.writerSheet(nbfbSixVo.getKcmc()).build();

            // 构建填充配置
            FillConfig fillConfig = FillConfig.builder()
                    .forceNewRow(true)
                    .direction(WriteDirectionEnum.VERTICAL)
                    .build();

            // 准备填充的数据
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("num", index);
            dataMap.put("kcmc", nbfbSixVo.getKcmc());
            dataMap.put("dw", nbfbSixVo.getDw());

            // 填充数据
            excelWriter.fill(dataMap, writeSheet);

            // 填充额外的数据
            excelWriter.fill(new FillWrapper(nbfbSixVo.getKcdkccdjList()), fillConfig, writeSheet);
        }

        try {
            // 完成写入
            excelWriter.finish();
            // 关闭资源
            baos.close();
            inputStream.close();
            templateStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
